package com.ykdl.member.kid.gears;

import java.util.ArrayList;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;

import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.MyPagerAdapter;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.fragments.GoodlifeFragment;
import com.ykdl.member.kid.fragments.HomeFragment;
import com.ykdl.member.kid.fragments.MessageFragment;
import com.ykdl.member.kid.fragments.MoreFragment;
import com.ykdl.member.kid.fragments.MyCircleFragment;
import com.ykdl.member.kid.gears.HomeActivity.getMessageCountTag;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.RequestAsAccessTokenUtil;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.member.kid.util.VersionUdgrateUtil;
import com.ykdl.member.views.IndexViewPager;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class HomeActivity extends BaseFragmentActivity {
	private ImageButton bar_homepage, bar_mycircle, bar_askdoctor,
			bar_personnews, menu_persfind;
	private IndexViewPager pager;
	private HttpBaseRequest request;
	private HomeMessageCount messageCountBean;
	private HomeFragment homeFragment = null;
	private MyCircleFragment myCircleFragment = null;
	private GoodlifeFragment goodlifeFragment = null;
	private MessageFragment messageFragment = null;
	private MoreFragment moreFragment = null;
	private ArrayList<Fragment> fragmentsList;
	private VersionUdgrateUtil versionUdgrateUtil;
	public ImageView red_point;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		inint();
		initMessageCount();// 初始化消息个数
		initViewPager();
		CheckVersionUpgrade();
		// Intent intent = new Intent(mContext, BindStoreActivity.class);
		// startActivityForResult(intent, 100);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		initMessageCount();// 初始化消息个数
		super.onResume();
	}

	/**
	 * 检测版本升级
	 */
	private void CheckVersionUpgrade() {
		versionUdgrateUtil = new VersionUdgrateUtil(this, false);
		versionUdgrateUtil.checkVersionUdgrateForTime();
	}

	private void initViewPager() {
		homeFragment = new HomeFragment();
		myCircleFragment = new MyCircleFragment();
		goodlifeFragment = new GoodlifeFragment();
		messageFragment = new MessageFragment();
		moreFragment = new MoreFragment();
		fragmentsList = new ArrayList<Fragment>();

		fragmentsList.add(homeFragment);
		fragmentsList.add(myCircleFragment);
		fragmentsList.add(goodlifeFragment);
		fragmentsList.add(messageFragment);
		fragmentsList.add(moreFragment);
		MyPagerAdapter adpater = new MyPagerAdapter(
				getSupportFragmentManager(), fragmentsList);
		pager.setAdapter(adpater);
		// 设置默认是第一页
		pager.setCurrentItem(0);
		// 设置ViewPager的页面切换监听事件，默认清空我的消息页被选中
		pager.setOnPageChangeListener(new MyOnPageChangeListener());
		// ViewPager 预加载的处理（我的消息，我的通知和我的私信都进行预加载）
		pager.setOffscreenPageLimit(4);

	}

	public class MyOnPageChangeListener implements OnPageChangeListener {
		Animation animation = null;

		@Override
		public void onPageSelected(int arg0) {
			switch (arg0) {
			case 0:
				setSelectedID(R.id.bar_homepage);
				break;
			case 1:
				setSelectedID(R.id.bar_mycircle);
				break;
			case 2:
				setSelectedID(R.id.bar_askdoctor);
				break;
			case 3:
				setSelectedID(R.id.bar_personnews);
				break;
			case 4:
				setSelectedID(R.id.menu_persfind);
				break;

			default:
				break;
			}

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

	}

	public void initMessageCount() {
		AccessTokenKeeper keeper = new AccessTokenKeeper(this);
		if (keeper.getmisAnonymous())
			return;
		if (!isConnect())
			return;
		String url = KidConfig.UNREAD_NEWS_COUNT;
		HttpParameters bodyParams = new HttpParameters();
		request = Wxxr.getInstance().postBaseRequest(url, bodyParams, null);
		TaskManager.startHttpRequest(request, new getMessageCountTag(),
				HomeMessageCount.class);

	}

	class getMessageCountTag implements ITag {
		@Override
		public void refreshUI(Object t, DataState ds) {
			if (null != t && t instanceof HomeMessageCount) {
				messageCountBean = (HomeMessageCount) t;
				if (messageCountBean.isExpired()) {
					RequestAsAccessTokenUtil.getInstance(mContext)
							.refreshTokenRequest(request, this,
									HomeMessageCount.class);
				} else {
					settingMessageCount();
				}

			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return true;
		}

		@Override
		public void refreshCancel() {
		}

	}

	/**
	 * 设置信息数量汇总
	 */
	public void settingMessageCount() {
		if (messageCountBean.getUnread_count() > 0) {
			red_point.setVisibility(View.VISIBLE);
			MyPrefs.setMessageCount(this, "1");
		} else {
			red_point.setVisibility(View.GONE);
			MyPrefs.setMessageCount(this, null);
		}
	}

	private void inint() {
		// TODO Auto-generated method stub
		red_point = (ImageView) findViewById(R.id.red_point); // 消息小红点
		bar_homepage = (ImageButton) findViewById(R.id.bar_homepage);// 首页
		bar_homepage.setSelected(true);
		bar_mycircle = (ImageButton) findViewById(R.id.bar_mycircle);// 姐妹聊
		bar_askdoctor = (ImageButton) findViewById(R.id.bar_askdoctor);// 惠生活
		bar_personnews = (ImageButton) findViewById(R.id.bar_personnews); // 消息
		menu_persfind = (ImageButton) findViewById(R.id.menu_persfind);// 更多

		bar_homepage.setOnClickListener(new MyOnClickListener(0));
		bar_mycircle.setOnClickListener(new MyOnClickListener(1));
		bar_askdoctor.setOnClickListener(new MyOnClickListener(2));
		bar_personnews.setOnClickListener(new MyOnClickListener(3));
		menu_persfind.setOnClickListener(new MyOnClickListener(4));

		pager = (IndexViewPager) findViewById(R.id.tabpager);
		pager.setScanScroll(true);
	}

	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.bar_homepage: // 首页
				setSelectedID(R.id.bar_homepage);
				pager.setCurrentItem(0, false);
				break;
			case R.id.bar_mycircle: // 姐妹聊
				setSelectedID(R.id.bar_mycircle);
				pager.setCurrentItem(1, false);
				// Intent intent = new
				// Intent(HomeActivity.this,ToAskDoctorActivity.class);
				// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				// HomeActivity.this.startActivity(intent);
				break;
			case R.id.bar_askdoctor: // 惠生活
				setSelectedID(R.id.bar_askdoctor);
				pager.setCurrentItem(2, false);
				break;
			case R.id.bar_personnews: // 消息
				setSelectedID(R.id.bar_personnews);
				messageFragment.refreshMessageFragment();
				pager.setCurrentItem(3, false);
				break;
			case R.id.menu_persfind: // 更多
				setSelectedID(R.id.menu_persfind);
				pager.setCurrentItem(4, false);
				break;

			default:
				break;
			}
		}
	};

	public void setSelectedID(int id) {

		bar_homepage.setSelected(false);
		bar_mycircle.setSelected(false);
		bar_askdoctor.setSelected(false);
		bar_personnews.setSelected(false);
		menu_persfind.setSelected(false);
		// bar_personnews.setImageResource(R.drawable.men_personnews);
		if (id == R.id.bar_homepage) {
			bar_homepage.setSelected(true);
			/*
			 * initMessageCount(); if(messageCountBean.getUnread_count()>0){
			 * bar_personnews
			 * .setImageResource(R.drawable.men_personnews_havenew); }else{
			 * bar_personnews.setImageResource(R.drawable.men_personnews); }
			 */
		}
		if (id == R.id.bar_mycircle) {
			bar_mycircle.setSelected(true);
			/*
			 * initMessageCount(); if(messageCountBean.getUnread_count()>0){
			 * bar_personnews
			 * .setImageResource(R.drawable.men_personnews_havenew); }else{
			 * bar_personnews.setImageResource(R.drawable.men_personnews); }
			 */
		}
		if (id == R.id.bar_askdoctor) {
			bar_askdoctor.setSelected(true);
			/*
			 * initMessageCount(); if(messageCountBean.getUnread_count()>0){
			 * bar_personnews
			 * .setImageResource(R.drawable.men_personnews_havenew); }else{
			 * bar_personnews.setImageResource(R.drawable.men_personnews); }
			 */
		}
		if (id == R.id.bar_personnews) {
			// 有未读消息？？
			bar_personnews.setSelected(true);
			// initMessageCount();
			// bar_personnews.setImageResource(R.drawable.men_personnews_now);
			/*
			 * if(messageCountBean.getUnread_count()>0){ //
			 * message_bt.setSelected(true); //
			 * bar_personnews.setImageResource(R.drawable.bar_check_havenews);
			 * }else{ // message_bt.setSelected(false);
			 * bar_personnews.setImageResource(R.drawable.men_personnews_now); }
			 */
		}
		if (id == R.id.menu_persfind) {
			menu_persfind.setSelected(true);
			/*
			 * initMessageCount(); if(messageCountBean.getUnread_count()>0){
			 * bar_personnews
			 * .setImageResource(R.drawable.men_personnews_havenew); }else{
			 * bar_personnews.setImageResource(R.drawable.men_personnews); }
			 */
		}
	}

	long exitTime;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(this, "请再按一次退出APP!", 0).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				ResoureUtil.exit();
				System.exit(0);
			}

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void setAtItem() {
		setSelectedID(R.id.bar_askdoctor);
		pager.setCurrentItem(2);
	}

}
